//
//  ApplyForRefundVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/16.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "ApplyForRefundVC.h"
#import "ForRefundTopCell.h"
#import "ForRefundMiddelCell.h"
#import "ForRefundBottomCell.h"
#import "MyInfoFooterView.h"

#import "RefundFooterVeiw.h"

#import <LEEAlert/LEEAlert.h>
#import "SelectedListView.h"
@interface ApplyForRefundVC ()
@property (nonatomic, strong) MyInfoFooterView *footerView;
@property (nonatomic, strong) RefundFooterVeiw *footerView2;
/** <#note#> */

@end

@implementation ApplyForRefundVC

- (ApplyRefundParmModel *)parmModel{
    if (!_parmModel) {
        _parmModel = [[ApplyRefundParmModel alloc]init];
        _parmModel.tag = @"0";
    }
    
    
    return _parmModel;
}



- (MyInfoFooterView *)footerView{
    
    if (!_footerView) {
        
        MyInfoFooterView *temp = (MyInfoFooterView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([MyInfoFooterView class]) owner:nil options:nil].firstObject;
        
        temp.bottomLabel.hidden = YES;
        
        temp.topBtn.backgroundColor = themeColor;
        
        [temp.topBtn setTitle:@"提交退款申请" forState:UIControlStateNormal];
        
        [temp.topBtn addTarget:self action:@selector(nextStepDidClick) forControlEvents:UIControlEventTouchUpInside];
        
        _footerView = temp;
        
    }
    
    return _footerView;
}



- (RefundFooterVeiw *)footerView2{
    
    if (!_footerView2) {
        
        RefundFooterVeiw *temp = (RefundFooterVeiw *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([RefundFooterVeiw class]) owner:nil options:nil].firstObject;
        
        _footerView2 = temp;
        
    }
    
    return _footerView2;
}


- (void)nextStepDidClick{
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"order_id"] = self.parmModel.order_id;
    parameters[@"order_goods_id"] = self.parmModel.order_goods_id;
    parameters[@"refund_require_money"] = self.parmModel.refund_require_money;
    parameters[@"refund_reason"] = self.parmModel.refund_reason;
    parameters[@"uid"] = myViewModel.user.uid;
    
    if (self.parmModel.refund_type == nil) {
        
        [self showInformation:@"请选择处理方式..."];
        
        return;
    }
    
    if ([self.parmModel.refund_type containsString:@"并且"]) {
        parameters[@"refund_type"] = @"2";
        
    } else {
        
        parameters[@"refund_type"] = @"1";
        
    }
    
    
    if (self.parmModel.refund_reason == nil) {
        
        [self showInformation:@"请选择退款原因..."];
        
        return;
    }
    
    
    if (self.parmModel.refund_require_money == nil) {
        
        [self showInformation:@"请填写退款金额..."];
        
        return;
    }
    
    
    //判断是否是纯数字
    
    if( [self isPureInt:self.parmModel.refund_require_money] || [self isPureFloat:self.parmModel.refund_require_money])
        
    {
        
        
        if (self.parmModel.refund_require_money.floatValue > self.parmModel.placehoder.floatValue) {
            
            [self showInformation:@"输入金额过大"];
            
            return;
        }
        
        
        if (!(self.parmModel.refund_require_money.floatValue > 0)) {
            
            [self showInformation:@"输入金额非法"];
            
            return;
        }
        
        [SVProgressHUD showWithStatus:@"正在提交申请..."];
        
        MJWeakSelf;
        [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Order/orderGoodsRefund" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
            
            if (!error) {
                
                [SVProgressHUD dismiss];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"DidApplyForRefundSuccsece" object:nil];
                
                weakSelf.parmModel.tag = @"1";
                
                self.tableView.tableFooterView = self.footerView2;
                
                [weakSelf.tableView reloadData];
                
                
            } else {
                [SVProgressHUD showInfoWithStatus:error.domain];
            }
            
            
        }];
        
        
        
        
        
        
    
    }
    
    
    

    
    




    
//
//
//    [self.tableView reloadData];
    
    
}
    
    
    
    
    
    - (BOOL)isPureInt:(NSString*)string{
        
        NSScanner* scan = [NSScanner scannerWithString:string];
        
        int val;
        
        return [scan scanInt:&val] && [scan isAtEnd];
        
    }
    
    
    //判断是否为浮点形：
    
    - (BOOL)isPureFloat:(NSString*)string{
        
        NSScanner* scan = [NSScanner scannerWithString:string];
        
        float val;
        
        return [scan scanFloat:&val] && [scan isAtEnd];
        
    }
    





- (void)showInformation:(NSString *)str{
    
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    
    //    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //
    //
    //    }];
    
    
    //    [contr addAction:action2];
    [contr addAction:action1];
    
    [self presentViewController:contr animated:YES completion:nil];
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setNav];
    
    [self.tableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:[BaseTableViewCell identifierStr]];
    
    self.tableView.backgroundColor = viewBgGrey;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ForRefundTopCell class]) bundle:nil] forCellReuseIdentifier:[ForRefundTopCell identifierStr]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ForRefundMiddelCell class]) bundle:nil] forCellReuseIdentifier:[ForRefundMiddelCell identifierStr]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ForRefundBottomCell class]) bundle:nil] forCellReuseIdentifier:[ForRefundBottomCell identifierStr]];
    
    self.tableView.tableFooterView = self.footerView;

}



- (void)setNav{
    
    self.navigationItem.title = @"申请退款";
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateHighlighted];
    
    [but addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    
    but.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //        but.backgroundColor = [UIColor redColor];
    
    but.frame = CGRectMake(0, 0, 44, 44);
    but.contentEdgeInsets = UIEdgeInsetsMake(11, -10, 11, 22);
    
    UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc]initWithCustomView:but];
    
    
    self.navigationItem.leftBarButtonItem = returnButtonItem;
}


- (void)back{
    
    [self.view endEditing:YES];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([self.parmModel.tag isEqualToString:@"0"]) {
        return 5;
    } else {
        return 1;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.parmModel.tag isEqualToString:@"0"]) {
        
        
        if (indexPath.row == 0) {
            ForRefundTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ForRefundTopCell identifierStr]];
            
            tableCell.model = self.parmModel;
            
            return tableCell;
        } else  if (indexPath.row == 1) {
            ForRefundMiddelCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ForRefundMiddelCell identifierStr]];
            
            tableCell.index = indexPath;
            
            tableCell.model = self.parmModel;
            
            return tableCell;
        }else if (indexPath.row == 2) {
            ForRefundMiddelCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ForRefundMiddelCell identifierStr]];
            
            tableCell.index = indexPath;
            
            tableCell.model = self.parmModel;
            
            return tableCell;
        }else if (indexPath.row == 3) {
            
            ForRefundBottomCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ForRefundBottomCell identifierStr]];
            
            tableCell.model = self.parmModel;
            
            return tableCell;
            
        }else{
            
            BaseTableViewCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[BaseTableViewCell identifierStr]];
            
            
            return tableCell;
            
        }
        
    } else {
        
        
        ForRefundTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ForRefundTopCell identifierStr]];
        
        tableCell.model = self.parmModel;
        
        return tableCell;
        
    }
    
   
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if ([self.parmModel.tag isEqualToString:@"0"]) {
        if (indexPath.row == 0) {
            
            
            return 90;
            
        }else{
            
            if (indexPath.row == 4) {
                return 0;
            } else {
                return 52;
            }
            
            
        }
    } else {
        
        return 90;
    }
    
    
   
    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    
    if ([self.parmModel.tag isEqualToString:@"0"]) {
        
        
        if (indexPath.row == 1 ) {
            
            [self index1DidTap];
            
        } else if (indexPath.row == 2) {
            [self index2DidTap];

        }
        
    }
  
    
}








- (void)index1DidTap{
    
    
    SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
    
    view.isSingle = YES;
    
    
    view.array = @[[[SelectedListModel alloc] initWithSid:0 Title:@"我要退款,但不退货"],
                   [[SelectedListModel alloc] initWithSid:1 Title:@"我要退款,并且退货"]];
    
    
    MJWeakSelf;
    view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
        
        [LEEAlert closeWithCompletionBlock:^{
            
            
            weakSelf.parmModel.refund_type = array.firstObject.title;

            [weakSelf.tableView reloadData];
            
            
            
        }];
        
    };
    
    [LEEAlert alert].config
    .LeeTitle(@"选择处理方式")
    .LeeItemInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeCustomView(view)
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
}







- (void)index2DidTap{
    
    
    SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
    
    view.isSingle = YES;
    
    view.array = @[[[SelectedListModel alloc] initWithSid:0 Title:@"买/卖双方协商一致"],
                   [[SelectedListModel alloc] initWithSid:1 Title:@"买错/多买/不想要"],
                   [[SelectedListModel alloc] initWithSid:0 Title:@"商品质量问题"],
                   [[SelectedListModel alloc] initWithSid:1 Title:@"未收到货品"],
                   [[SelectedListModel alloc] initWithSid:1 Title:@"其他"]
                   ];
    
    
    MJWeakSelf;
    view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
        
        [LEEAlert closeWithCompletionBlock:^{
            
            weakSelf.parmModel.refund_reason = array.firstObject.title;
            
            [weakSelf.tableView reloadData];
            
            
            
        }];
        
    };
    
    [LEEAlert alert].config
    .LeeTitle(@"选择退款原因")
    .LeeItemInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeCustomView(view)
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
}





- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
     [self.view endEditing:YES];
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
